/******************************
 ***    ImageConvolution.c  ***
 *****************************/
 
#include "ImageType/ImageType.h"
#include        "Umat/Mat2fType.h"
 
 
 
image_type *
image_convolution( image_type *sim, mat2f_type *m )
{
image_type	*im;
u_char  *p,	*sp;
int     row,    col,    i,      j;
int	d,	val;
 

	if( sim->depth != 1 )	return( NULL );


	row = IMAGE_ROW(sim);
	col = IMAGE_COLUMN(sim);

	im = image_create( row, col, 1, 1, NULL );
 
	d = m->ni / 2;
 
	sp = (u_char *)sim->data;
	p = (u_char *)im->data;
	for( i = 0 ; i < im->row ; i++ )
		for( j = 0 ; j < im->column ; j++ ){

			if( i-d < 0 || i + d > row || j-d < 0 || j + d > col ){
					*p = *sp ;
					p++;
					sp++;
					continue;
			}
 
			val = image_mat2f_inner( sim, i-d, j-d, m );
			*p = PUSH_TO_RANGE( val, 0, 255 );

			p++;
			sp++;
		}

	return( im );
}




float
image_mat2f_inner( image_type *im, int i0, int j0, mat2f_type *m )
{
u_char  *p;
int     i,      j;
float	*mf,	sum = 0;

	

	mf = m->f;
	for( i = i0 ; i < i0+m->ni ; i++ ){
		p = IMAGE_PIXEL( im, i, j0 );
		for( j = j0 ; j < j0+m->nj ; j++ ){

			sum += (*mf) * (*p);

			p++;
			mf++;
		}
	}

	return( sum );
}

